//index.js
//获取应用实例
const app = getApp();
// const Uploader = require('../../resources/bce-bos-uploader-lite/uploader.js');
const StsTokenMananger = require('../../resources/bce-bos-uploader-lite/sts_token_manager');
// const BosClient = require('../../resources/bce-bos-uploader-lite/bce-sdk-js/bos_client.js');
const Auth = require('../../resources/bce-bos-uploader-lite/bce-sdk-js/auth.js');
const Base64 = require('../../resources/bce-bos-uploader-lite/base64.js');
const fs = wx.getFileSystemManager();
Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  bindNavigator: function (e) {
    wx.navigateTo({
      url: e.target.dataset.url,
    })
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  bindGetStsToken: function() {
    //AccessDenied
    wx.chooseImage({
      success: function(res) {
        let options = {
          uptoken_url: 'http://172.17.150.42:8080/web/api/bos/ack.do'
        };
        //Authorization
        let token = new StsTokenMananger(options);
        token.get().then(function(result) {
          var key = "test/res/image/" + new Date().getTime() + '.jpg';
          var policy = '{"conditions":[{"bucket":"zskd-pub"},{"key":"' + key + '"}]}';
          var sessionToken = result.SessionToken;
          var accessKeyId = result.AccessKeyId,
            secretAccessKey = result.SecretAccessKey;
          var auth = new Auth(accessKeyId, secretAccessKey);
          var date = new Date();
          policy = Base64.encode(policy);
          var Authorization = auth.generateAuthorization('POST', '', {
            policy: policy
          }, {
            'x-bce-security-token': sessionToken,
            'Host': 'zskd-pub.bj.bcebos.com',
            'x-bce-date': date.toISOString(),
          }, date.getTime() / 1000, 1800, [
            'x-bce-security-token',
            'Host',
            'x-bce-date'
          ]);
          //accessKey
          wx.uploadFile({
            url: 'https://zskd-pub.bj.bcebos.com',
            filePath: res.tempFilePaths[0],
            name: 'file',
            header: {
              'Authorization': Authorization,
              'x-bce-security-token': sessionToken,
              'x-bce-date': date.toISOString()
            },
            formData: {
              // accessKey: accessKeyId,
              // policy:policy,
              //signature: auth.hash(policy,secretAccessKey),
              key: key

            },
            success: function(res) {
              console.log(res);
            }
          });
        });
      },
    })

  },
  bindUpload: function() {
    //binary
    wx.chooseImage({
      success: function(res) {
        let options = {
          uptoken_url: 'http://172.17.150.42:8080/web/api/bos/getSessionToken.do'
        };
        //Authorization
        let token = new StsTokenMananger(options);
        token.get().then(function(result) {
          var key = "test/res/image/" + new Date().getTime() + '.jpg';
          var sessionToken = result.SessionToken;
          var accessKeyId = result.AccessKeyId,
            secretAccessKey = result.SecretAccessKey;
          var auth = new Auth(accessKeyId, secretAccessKey);
          var date = new Date();
          fs.readFile({
            filePath: res.tempFilePaths[0],
            success: function(buffer) {
              var data = buffer.data,
                contentLength = data.length;
              var Authorization = auth.generateAuthorization('PUT', '/' + key, {}, {
                'x-bce-security-token': sessionToken,
                'Host': 'zskd-pub.bj.bcebos.com',
                'Content-Type': 'image/jpg',
                'x-bce-date': date.toISOString(),
              }, date.getTime() / 1000, 1800, [
                'x-bce-security-token',
                'Host',
                'Content-Type',
                'x-bce-date'
              ]);
              wx.request({
                url: 'https://zskd-pub.bj.bcebos.com/' + key,
                data: data,
                method: 'PUT',
                header: {
                  'content-type': 'image/jpg',
                  'Authorization': Authorization,
                  'x-bce-security-token': sessionToken,
                  'x-bce-date': date.toISOString()
                },
                success: function(res) {
                  console.log(res);
                },
                fail: function() {
                  console.log('fail');
                },
                complete: function() {
                  console.log('complete');
                }
              });
            }
          });
        });
      },
    });
  },
  onLoad: function() {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})